<?php
namespace App\Libs\Passport;
use \App\Libs\Base\Constant;
use \App\Libs\Exception\RuntimeException;
class Activation extends \App\Libs\Base\Singleton
{
    public static $prefix = 'active:code:';
    private $userTable = 't_hera_user';

    private static function getCode($uid, $email) {
        return \App\Libs\Helper\CryptHelper::encrypt($uid . ':' . $email . ':' . time() . ':' . mt_rand(1, 1000));
    }

    public static function generate($uid, $email) {
        $code = self::getCode($uid, $email);
        //\App\Libs\Cache\Memcached::set(self::$prefix . $code, array('uid' => $uid, 'email' => $email), 86400);

        return $code;
    }

    public function active($code) {
        //$uinfo = \App\Libs\Cache\Memcached::get(self::$prefix . $code);
        $uinfo = \App\Libs\Helper\CryptHelper::decrypt($code);
        if (empty($uinfo)) {
            throw new RuntimeException(Constant::message(Constant::ACTIVE_CODE_EXPIRE), Constant::ACTIVE_CODE_EXPIRE);
        }
        list($id, $email, $time, $rand) = explode(':', $uinfo);
        if (time() - $time > 1800) {
            throw RuntimeException::instance(Constant::ACTIVE_CODE_EXPIRE);
        }
        $info = array('id' => $id);
        $info['is_active'] = 1;
        $info['atime'] = date('Y-m-d H:i:s');
        $sql = "UPDATE {$this->userTable} SET is_active=:is_active,atime=:atime WHERE id=:id";
        return \App\Libs\DB\HeraPdo::instance()->write($sql, $info);
    }
}
